// 1. npm i ml-ckmeans
// import ckmeans from 'ckmeans';
import ckmeans from 'https://cdn.jsdelivr.net/npm/ckmeans@2.1.0/+esm'

function minMaxFast(arr) {
  let min = Infinity, max = -Infinity;
  for (let i = 0; i < arr.length; i++) {
    const v = arr[i];
    if (v < min) min = v;
    if (v > max) max = v;
  }
  return [min, max];
}

function fastJenksBig(data, k, binCount = 512) {
  // 1. 直方图预聚合：O(n)
  const [min, max] = minMaxFast(data);
  console.log(min, max);
  const step = (max - min) / binCount;
  const hist = new Array(binCount).fill(0);
  data.forEach(v => {
    const idx = Math.min(binCount - 1, Math.floor((v - min) / step));
    hist[idx]++;
  });

  // 2. 桶中心
  const centers = hist.map((_, i) => min + step * (i + 0.5));

  // 3. 近似自然分段：O(g²·k)
  const clusters = ckmeans(centers, k, hist);

  return clusters;
}

/* ==== DEMO ==== */
// const big = Array.from({ length: 1_000_000 }, () => Math.random() * Math.random() * 1000);
// console.time('fastJenksBig');
// console.log(fastJenksBig([...big, 100000], 10));
// console.timeEnd('fastJenksBig'); // ~350 ms

export { fastJenksBig }
